import Vue from 'vue';
const that = Vue.prototype;
// 错误column
const errorsColumn = {
  title: '禁止提交原因',
  key: 'unSubmitReason',
  fixed: 'left',
  sortable: true,
  errorTip: true,
  notShowTip: true,
}
// 异常column
const tipsColumn = {
  title: '异常提示',
  key: 'abnormalTip',
  fixed: 'left',
  sortable: true,
  errorTip: true,
  notShowTip: true,
}
// 有禁止提交原因
const hasErrorsByUnSubmit = (list) => {
  return list.some(item => item.validation?.errors);
}
// 有异常提示
const hasTipsByWarning = (list) => {
  return list.some(item => item.validation?.tips);
}
const getTableDataByJoinStr = (tableData) => {
  return tableData.reduce((value, item) => {
    value.push({
      ...item,
      unSubmitReason: item.validation?.errors ? item.validation?.errors.join('，') : '',
      abnormalTip: item.validation?.tips ? item.validation?.tips.join('，') : ''
    });
    return value;
  }, []);
}
// 禁止提交原因确认弹框
const openConfirmByUnSubmitReason = () => {
  that.$confirm(
    '存在禁止提交原因，无法提交单据，请在详情页中查看具体原因',
    '提交错误提示',
    {
      type: 'warning',
      showCancelButton: false
    }
  ).then(() => {
  }).catch(() => {});
}
// 异常提示确认弹框
const openConfirmByAbnormalTips = (submitPriceData) => {
  that.$confirm(
    '存在异常提示，是否仍要提交？',
    '提交异常提示',
    {
      type: 'warning',
      cancelButtonText: '查看详情'
    }
  ).then(() => {
    submitPriceData();
  }).catch(() => {});
}

// 获取更新后的表列
const getUpdateColumns = (tableColumns, type) => {
  const initColumns = _.cloneDeep(tableColumns).filter(item => !['unSubmitReason', 'abnormalTip'].includes(item.key));
  const tipsColumns = [tipsColumn, ...initColumns];
  const errsColumns = [errorsColumn, tipsColumn, ...initColumns];
  const columnsTypes = {
    'error': errsColumns,
    'tip': tipsColumns,
    'normal': initColumns
  }
  return columnsTypes[type] || [];
}

// 提交价格校验
const validatePriceDataBySubmit = ({
  tableData, tableColumns, setTableDataAndColumns, submitPriceData
}) => {
  if (!tableData) { return false; }
  if (hasErrorsByUnSubmit(tableData)) {
    setTableDataAndColumns({
      columns: getUpdateColumns(tableColumns, 'error'),
      data: getTableDataByJoinStr(tableData)
    });
    openConfirmByUnSubmitReason();
    return false;
  }
  if (hasTipsByWarning(tableData)) {
    setTableDataAndColumns({
      columns: getUpdateColumns(tableColumns, 'tip'),
      data: getTableDataByJoinStr(tableData)
    });
    openConfirmByAbnormalTips(submitPriceData);
    return false;
  }
  setTableDataAndColumns({
    columns: getUpdateColumns(tableColumns, 'normal'),
    data: getTableDataByJoinStr(tableData)
  });
  return true;
}
export {
  errorsColumn,
  tipsColumn,
  hasErrorsByUnSubmit,
  hasTipsByWarning,
  getTableDataByJoinStr,
  validatePriceDataBySubmit
}
